package com.examples.chartdirector.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class BiyingHttpServiceImplement implements IBiyingService {
	private static final String formatUrl = APP_DEFAULT_DOMAIN + "/hsstock/history/%s/%s/%s/" + TestLicense;

	@Override
	public void historyQuery(String code, Level level, Ex_rights type, int limit,OnResponseListener responseListener)
			throws Exception {
		responseListener.onNext(
				request("GET",
						limit > 0 ? String.format(formatUrl + "?lt=%d", code, level.level, type.name(), limit)
								: String.format(formatUrl, code, level.level, type.name()),
						null)
				);
		
	}


	private HttpURLConnection connectTo(String method, String url) throws IOException {
		HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestMethod(method);
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.connect();
		return connection;
	}

  private String request(String method,String url, String params)throws IOException {
    StringBuffer sbf = new StringBuffer();
    String line = null;
    HttpURLConnection connection = connectTo(method, url);
    if (params != null) {
      PrintWriter  out = new PrintWriter(connection.getOutputStream());
      out.print(params);
      out.flush();
    }
    InputStream is = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    while ((line = reader.readLine()) != null) {
      sbf.append(line);
      sbf.append("\r\n");
    }
    reader.close();   
    connection.disconnect();
    return sbf.toString();
  }
}
